import { Rule, popMsg } from './Rule'
import { Log } from '../log';

const RegEx = {
  email: /\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/,
}
/**
 * 数据格式校验
 */
export class FormatRule implements Rule {
  validate(val: any, rule: any, form: any): boolean {
    let type = rule['format']
    if (type) {
      let exp = RegEx[type];
      if (!exp) {
        Log.error('未支持的校验类型忽略', type)
        return true;
      }
      try {
        let regEx = new RegExp(exp)
        if (!regEx.test(val)) {
          popMsg(rule['errorMessage'])
          return false;
        }
      } catch (e) {
        Log.error('校验规则非正则表达式忽略', exp, e)
      }
    }
    return true;
  }
}